package cn.itcast.com.MyQueueByLinkedlist;

import cn.itcast.com.MyLinkedList.MyLinkedList;
import lombok.Data;

import java.util.EmptyStackException;
import java.util.LinkedList;

/**
 * Created by 郭浩 on 2020/8/18 19:30
 */
public class MyQueue<E> extends LinkedList<Object> {
    //初始化头尾
    private Node head;
    private Node end;
    //长度
    private int size = 0;

    //构造方法,初始化为null
    public MyQueue(){
        end = new Node(null,null);
        head = new Node(null,null);
    }

    class Node{
        E value;
        Node next;

        public Node(E value, Node next) {
            this.value = value;
            this.next = next;
        }

        public Node(E value){
            this.value = value;
        }
    }



    //入队
    public void enqueue(E e){
        //因为是链表，不会出现空间不足，扩容
        //先判断是不是空的
        if (isEmpty()){
            //空的话.新建一个node，然后将头尾的next都指向这个新节点
            Node node = new Node(e, null);
            head.next = node;
            end.next = node;
        }else {
            //若非空，则将最后一个元素和end指向这个节点
            Node node = new Node(e,null);
            //由end指向的节点为最后一个节点
            end.next.next = node;
            end.next = node;
        }
        size++;
    }

    //出队
    public E dequeue(){
        if (isEmpty()){
            throw new EmptyStackException();
        }else {
            //取得head指向的节点的value，将head指向下一个节点
            E value = head.next.value;
            head.next = head.next.next;
            size--;
            return value;
        }
    }
    @Override
    public String toString() {
        StringBuilder sb=new StringBuilder();
        sb.append("[");

        if (!isEmpty()){
            MyQueue.Node node=head.next;

            while (node!=end){

                sb.append(node.value+",");
                node=node.next;

            }
            //包括左边，不包括右边 “123456”  0 5
            //
            sb.delete(sb.length()-1,sb.length());

        }


        sb.append("]");
        return  sb.toString();
    }



    //判断是否为空
    public boolean isEmpty(){
        return size == 0;
    }

    //长度
    public int getSize(){
        return size;
    }


}
